import React, { useEffect, useState } from "react";
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text, Button, Navigator, } from '@tarojs/components'
import { Image, Popup, Icon, Divider, Toast, Checkbox } from '@antmjs/vantui'
import { useDispatch } from "react-redux";
import { appLogin, getUserDetail, getUserPhone, bindUserPhone } from "@/services"

import './index.scss'

function Home() {
  const dispatch = useDispatch()
  const [getPhoneVisible, setGetPhoneVisible] = useState(false)
  const [checkboxValue, setCheckboxValue] = useState(false)
  const navPosition = Taro.getStorageSync('nav-position') ? JSON.parse(Taro.getStorageSync('nav-position')) : {}
  const router = useRouter()
  useEffect(() => {
    router?.path && Taro.setStorageSync('login-route', router.path)
    return () => {
      Taro.removeStorageSync('login-route')
    }
  }, [router])
  /**
   * @description: 获取并绑定用户手机号
   * @event:
   * @param {*} e
   * @return {*}
   */
  const getPhoneNumber = (e) => {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let code = e.detail.code
      getUserPhone({ appletCode: code, source: 2 }).then(resp => {
        if (resp.data?.bindId) {
          bindUserPhone({ bindId: resp.data.bindId }).then((res) => {
            const data = res.data
            // 绑定手机号后更新token
            data?.token && Taro.setStorageSync('auth-token', data.token)
            Taro.switchTab({
              url: "/pages/tabbar/home/index"
            })
          }, () => {

          })
        }

      }, err => {
        console.log(err);
      })
    }
  }
  // 一键登录
  const userLogin = () => {
    if (!checkboxValue) {
      Toast.show('请先同意并勾选用户协议')
      return
    }

    Taro.login().then(res => {
      let params = {
        appletToken: res.code,
        source: 2
      }
      appLogin(params).then(resp => {
        const data = resp.data
        if (resp.code === 200) {
          data?.token && Taro.setStorageSync('auth-token', data.token)
          dispatch({
            type: 'certified/asyncGetUserDetail',
            callback: (res1) => {

              const user = res1.data?.user
              // unbindLogin是否绑定登录账号，1已绑定
              if (user) {
                if (user.unbindLogin == 1) {
                  Taro.switchTab({
                    url: "/pages/tabbar/home/index"
                  })
                } else {
                  setGetPhoneVisible(true)
                }
              }
            }
          })

        }

      })
    })
  }
  // 取消授权手机号
  const cancleBtn = () => {
    setGetPhoneVisible(false)
    Taro.removeStorageSync('auth-token')
    Toast.show('取消授权')
  }
  const checkboxChange = (e) => {

    setCheckboxValue(e.detail)
  }

  const LoginComp = () => {
    return (
      <View className='login'>
        <View className='login_top'>
          <View className='welcome'>欢迎来到道以星球</View>
          <View className='black4 text4 tip'>找私募<Text className='tip-line'></Text>查基金<Text className='tip-line'></Text>热门资讯</View>
        </View>
        {/* <Icon name='wechat' size='20px' className='icon' /> */}
        <Button className='login-btn' onClick={() => userLogin()}>手机号快捷登录</Button>
        <View className='footer'>
          <Checkbox value={checkboxValue} iconSize='16px' checkedColor='#3C6BFF' onChange={(e) => checkboxChange(e)}>登录即表示已阅读并同意 <Navigator url='/mineDetail/serviceAgreement/index' className='link'>用户使用协议</Navigator> 、<Navigator url='/mineDetail/privacyPolicy/index' className='link'>隐私政策</Navigator></Checkbox>
        </View>
      </View>

    )
  }

  return (
    <>
      <View className='log-bgc'>
        <Image width='100vw' height='100%' fit='widthFix' src='https://static.hzddyy.com/taiyi/tt/login-bgc.png' />
        <View className='logo' style={{ top: `${navPosition.top + navPosition.height + 12 + 86}px` }}>
          <Image width='46px' height='50px' src={require("@/assets/images/logo.png")} />
          <Text className='logo_welcome'>道以星球</Text>
        </View>

      </View>
      <View className='step2'>
        {LoginComp()}
      </View>

      <Popup show={getPhoneVisible} round zIndex={10} onClose={() => setGetPhoneVisible(false)} className='popup2'>
        <View className='header-tip'>
          <Text>您还未绑定手机号</Text>
          <Text>需绑定手机号后继续使用一道投</Text>
        </View>
        <View className='tip-2'>
          <Button size='mini' hover-class='none' open-type='getPhoneNumber' onGetPhoneNumber={getPhoneNumber} onClick={() => setGetPhoneVisible(false)}>
            <Text> 前往绑定手机号</Text>
          </Button>
        </View>
        <View className='tip-3'>
          <Button className='cancle' size='mini' hover-class='none' onClick={() => cancleBtn()}>
            取消
          </Button>
        </View>


      </Popup>
      <Toast />
    </>




  )
}

export default Home
